"use client"
import { VideoSelect } from '@/lib/database/repositories/video-repository';
import HtmlLink from '@/app/components/common/html-link';
import VideoCard from './video-card';
import { useEffect, useState, useCallback } from 'react';
import { dynamicWidth } from '@/lib/utils/utils';

interface CategorySectionProps {
  title: string;
  moreLink?: string;
  videos: VideoSelect[];
}

export default function CategorySection({ title, moreLink, videos }: CategorySectionProps) {
  // 如果没有数据，显示标题和暂无数据提示
  if (!videos.length) {
    return (
      <section className="py-4 sm:py-6">
        <div className="flex items-center justify-between mb-3 sm:mb-4">
          <h2 className="text-xl font-bold text-white relative pl-3 before:content-[''] before:absolute before:left-0 before:top-1/2 before:-translate-y-1/2 before:h-5 before:w-1 before:bg-accent-primary before:rounded-full">{title}</h2>
          {moreLink && (
            <HtmlLink
              href={moreLink}
              className="flex items-center text-gray-400 hover:text-accent-primary text-sm transition-colors font-medium"
            >
              <span>查看更多</span>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-4 w-4 ml-1 transition-transform group-hover:translate-x-0.5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </HtmlLink>
          )}
        </div>
        
        <div className="py-8 text-center">
          <p className="text-gray-400">暂无数据</p>
        </div>
      </section>
    );
  }
  
  // 使用客户端组件来处理响应式布局
  return (
    <section className="py-4 sm:py-6">
      <div className="flex items-center justify-between mb-3 sm:mb-4">
        <h2 className="text-xl font-bold text-white relative pl-3 before:content-[''] before:absolute before:left-0 before:top-1/2 before:-translate-y-1/2 before:h-5 before:w-1 before:bg-accent-primary before:rounded-full">{title}</h2>
        {moreLink && (
          <HtmlLink
            href={moreLink}
            className="flex items-center text-gray-400 hover:text-accent-primary text-sm transition-colors font-medium"
          >
            <span>查看更多</span>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-4 w-4 ml-1 transition-transform group-hover:translate-x-0.5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 5l7 7-7 7"
              />
            </svg>
          </HtmlLink>
        )}
      </div>
      
      <div className="overflow-x-safe sm:overflow-visible -mx-2 sm:mx-0">
        <div className="flex sm:grid sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-2.5 sm:gap-4 md:gap-5 pb-1 sm:pb-0 overflow-x-auto no-scrollbar">
          <ResponsiveVideos videos={videos} />
        </div>
      </div>
    </section>
  );
}

// 客户端组件处理响应式显示逻辑

function ResponsiveVideos({ videos }: { videos: VideoSelect[] }) {
  const [visibleVideos, setVisibleVideos] = useState<VideoSelect[]>(videos);
  const [columnsPerRow, setColumnsPerRow] = useState(5); // 默认每行5个

  // 根据每行列数更新要显示的视频
  const updateVisibleVideos = useCallback(() => {
    const totalVideos = videos.length;
    const completeRows = Math.floor(totalVideos / columnsPerRow);
    const remainingVideos = totalVideos % columnsPerRow;
    
    // 如果最后一行不满，则只显示完整行的视频
    if (remainingVideos > 0 && remainingVideos < columnsPerRow) {
      setVisibleVideos(videos.slice(0, completeRows * columnsPerRow));
    } else {
      // 如果正好是完整行，或者最后一行是完整的，则显示所有视频
      setVisibleVideos(videos);
    }
  }, [videos, columnsPerRow]);

  // 监听窗口大小变化，更新每行显示的数量
  useEffect(() => {
    function updateColumnsCount() {
      // 使用动态宽度计算每个视频卡片的宽度
      const cardWidth = dynamicWidth(180); // 基础卡片宽度
      const gap = dynamicWidth(20);       // 间隙宽度，略微增加
      
      // 根据当前视口宽度和动态计算的卡片宽度确定每行列数
      const availableWidth = window.innerWidth;
      const columnsCount = Math.floor(availableWidth / (cardWidth + gap));
      
      // 根据计算结果和设备断点设置合理的列数
      if (window.innerWidth >= 1280) {
        setColumnsPerRow(Math.min(6, columnsCount)); // xl: 最多6列
      } else if (window.innerWidth >= 1024) {
        setColumnsPerRow(Math.min(5, columnsCount)); // lg: 最多5列
      } else if (window.innerWidth >= 768) {
        setColumnsPerRow(Math.min(4, columnsCount)); // md: 最多4列
      } else {
        setColumnsPerRow(Math.min(3, columnsCount)); // 默认/sm: 最多3列
      }
    }

    // 初始化
    updateColumnsCount();
    
    // 添加窗口大小变化的监听
    window.addEventListener('resize', updateColumnsCount);
    
    // 清理函数
    return () => window.removeEventListener('resize', updateColumnsCount);
  }, []);
  
  // 每当columnsPerRow或videos变化时重新计算
  useEffect(() => {
    updateVisibleVideos();
  }, [columnsPerRow, videos, updateVisibleVideos]);

  return (
    <>
      {visibleVideos.map((video) => (
        <div key={video.id} className="w-[34%] sm:w-full flex-shrink-0">
          <VideoCard video={video} />
        </div>
      ))}
    </>
  );
} 